import axios from "axios";
import router from "@/router";
import { ref } from 'vue';

const service = axios.create({
    timeout: 10 * 60 * 1000,
})

// 请求拦截
service.interceptors.request.use(
    (config) => {
        let token = window.localStorage.getItem("token");
        if(token){
            //请求头添加token
            config.headers['Authorization'] = token;
        }
        return config;
    },
    (error) => {
        //抛出错误
        return Promise.reject(error);
    },
)

//响应拦截
service.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        if(error.response?.status === 401){
            tokenFailureTreatment();
        }
        if(error.response?.status === 402){
            permissionDenied();
        }
        //错误信息统一处理
        if(error.response?.status === 500){
            ElMessage({
                message: error.response.data.message || '未知错误',
                type: 'error',
            })
        }
        //抛出错误
	    return Promise.reject(error);
    }
);

//权限不足
const permissionDenied = ()=> {
    ElMessage({
        message: "权限不足！",
        type: 'error',
    })
    router.push('/homePage');
}

//token失效处理方法
const tokenFailureTreatment = () => {
    //只弹框一次提示token失效
    if(document.getElementsByClassName('el-message-box').length === 0){
        ElMessageBox.confirm("登录失效","提示",{
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            router.push('/login');
        })
    }
};

export default service;